#pragma once

#include <iostream>
#include <string>
#include <errno.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;

namespace server
{
    static uint16_t gPort = 8080;
#define NUM 1024
    enum
    {
        SOCKET_ERR = 1,
        BIND_ERR,
        USAGE_ERR,
    };
    class UdpServer
    {
    public:
        UdpServer(const uint16_t &port = gPort)
            : _sock(-1), _port(port)
        {
        }

        ~UdpServer() {}

        void InitServer()
        {
            // 1.创建套接字
            _sock = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sock < 0)
            {
                // 创建套接字失败
                cerr << "Server err: " << errno << ":" << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            // 创建套接字成功
            cout << "Create Socket Success: " << _sock << endl;

            // 2.bind
            struct sockaddr_in locked; // 绑定当前主机  任意IP地址
            bzero(&locked, sizeof(locked));
            locked.sin_family = AF_INET;
            locked.sin_port = htons(_port);
            locked.sin_addr.s_addr = INADDR_ANY;

            int n = bind(_sock, (struct sockaddr *)&locked, sizeof(locked));
            if (n == -1)
            {
                // 绑定失败
                cerr << "Bind fail: " << errno << ":" << strerror(errno) << endl;
                exit(BIND_ERR);
            }
            cout << "Bind success!" << endl;
        }

        void start()
        {
            char buffer[NUM];
            while (1)
            {
                // 接受从客户端发来的数据
                struct sockaddr_in peer;
                socklen_t addrlen = sizeof(peer);

                ssize_t ret = recvfrom(_sock, buffer, sizeof buffer, 0, (struct sockaddr *)&peer, &addrlen);
                if (ret > 0)
                {
                    // 读取到数据
                    buffer[ret] = 0;
                    string clientIP = inet_ntoa(peer.sin_addr);
                    uint16_t clientPort = ntohs(peer.sin_port);
                    string message = buffer;

                    cout << "【" << clientIP << "】"
                         << "<->"
                         << "[" << clientPort << "]#-> " << message << endl;
                }
            }
        }

    private:
        int _sock;
        uint16_t _port; // 端口号
    };
}